{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from gs_quant.common import AggregationLevel\n",
    "from gs_quant.instrument import IRSwaption\n",
    "from gs_quant.backtests.triggers import PeriodicTrigger, PeriodicTriggerRequirements\n",
    "from gs_quant.backtests.actions import AddTradeAction\n",
    "from gs_quant.backtests.strategy import Strategy\n",
    "from gs_quant.backtests.generic_engine import GenericEngine\n",
    "from gs_quant.markets.portfolio import Portfolio\n",
    "from gs_quant.markets import HistoricalPricingContext\n",
    "from gs_quant.risk import IRDelta, Price, IRFwdRate, IRDailyImpliedVol, DollarPrice\n",
    "from datetime import date\n",
    "from gs_quant.datetime import business_day_offset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize session\n",
    "from gs_quant.session import GsSession\n",
    "GsSession.use(client_id=None, client_secret=None, scopes=('run_analytics',)) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Seagull params\n",
    "start = date(2020, 1, 1)\n",
    "end = business_day_offset(date.today(), -1, roll='preceding')\n",
    "\n",
    "# Add trades at what frequency\n",
    "freq_int = 1\n",
    "ramp_up_freq = 'w'\n",
    "freq = str(freq_int) + ramp_up_freq\n",
    "ramp_up_mult = 5\n",
    "ramp_up_period = ramp_up_mult * freq_int - 1\n",
    "holding_period = str(ramp_up_period) + ramp_up_freq\n",
    "strategy_notional = 100e6\n",
    "\n",
    "print(freq,holding_period)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Buy call spread, sell out-of-the-money put"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Portfolio def\n",
    "\n",
    "ccy = 'USD'\n",
    "expiry = '1y'\n",
    "tail = '10y'\n",
    "rate_option = 'USD-LIBOR-BBA'\n",
    "pay_rec = ['Receiver', 'Receive', 'Pay']\n",
    "strikes = ['A-50', 'A-25', 'A+50']\n",
    "direction = [-1, 1, -1]\n",
    "notional_inception = round(strategy_notional/(ramp_up_period+1), 0)\n",
    "\n",
    "port = []\n",
    "for i in range(len(pay_rec)):\n",
    "    opt = IRSwaption(pay_or_receive=pay_rec[i],\n",
    "                     termination_date=tail,\n",
    "                     notional_currency=ccy,\n",
    "                     expiration_date=expiry,\n",
    "                     notional_amount=direction[i]*notional_inception,\n",
    "                     strike = strikes[i],\n",
    "                     floating_rate_option=rate_option,\n",
    "                     name='swaption'+str(i))\n",
    "    port.append(opt)\n",
    "\n",
    "csa_string = ccy + '-1'    \n",
    "    \n",
    "seagull = Portfolio(port, name='Seagull')\n",
    "seagull.to_frame().transpose()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define deltas\n",
    "myParallelDelta = IRDelta(currency='local', aggregation_level=AggregationLevel.Type)\n",
    "\n",
    "# Define backtest\n",
    "trade_action = AddTradeAction(seagull, holding_period)\n",
    "trigger = PeriodicTrigger(PeriodicTriggerRequirements(start_date=start, end_date=end, frequency=freq), [trade_action])\n",
    "strategy = Strategy(None, trigger)\n",
    "\n",
    "# Select an engine\n",
    "GE = GenericEngine()\n",
    "backtest = GE.run_backtest(strategy, start=start, end=end,frequency=freq, risks=[Price, myParallelDelta], \n",
    "                           show_progress=True, csa_term=csa_string)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "backtest_summary = backtest.result_summary\n",
    "backtest_summary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "backtest_dates_reduced = backtest_summary.index\n",
    "\n",
    "with HistoricalPricingContext(dates = backtest_dates_reduced, show_progress=True):\n",
    "    ir_rates = seagull[0].calc([IRFwdRate, IRDailyImpliedVol])\n",
    "    entry = seagull.calc([DollarPrice])\n",
    "\n",
    "\n",
    "premium = entry.result().to_frame()\n",
    "raw_data = ir_rates.result().to_frame()\n",
    "raw_data[IRFwdRate] *= 1e4\n",
    "raw_data['entry_premium'] = (premium.iloc[:,0]+premium.iloc[:,1]+premium.iloc[:,2])\n",
    "raw_data.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "(backtest_summary['Cumulative Cash']/1e6).plot(title='Rolling Seagull vs Delta Proxy', legend=True, label='Strategy', figsize=(20, 10))\n",
    "(backtest_summary.iloc[5, 1] * (raw_data[IRFwdRate]-raw_data[IRFwdRate][0])/1e6).plot(legend=True, \n",
    "                            label=f'Delta Proxy ({round(backtest_summary.iloc[5, 1]/1e3, 0)}k per bp)')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}